package com.free.gulimall.cart.controller;


import com.free.common.to.UserInfoTo;
import com.free.gulimall.cart.interceptor.CartInterceptor;
import com.free.gulimall.cart.service.CartService;
import com.free.gulimall.cart.vo.Cart;
import com.free.gulimall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;

    @RequestMapping("/cart.html")
    public String getCartList(Model model) {
        UserInfoTo userInfoTo= CartInterceptor.threadLocal.get();
        Cart Cart=cartService.getCart();
        model.addAttribute("cart", Cart);
        return "cartList";
    }

//    @RequestMapping("/success.html")
//    public String success() {
//        return "success";
//    }
//
    /**
     * 添加商品到购物车
     * RedirectAttributes.addFlashAttribute():将数据放在session中，可以在页面中取出，但是只能取一次
     * RedirectAttributes.addAttribute():将数据放在url后面
     * @return
     */
    @RequestMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes attributes) {
        cartService.addToCart(skuId, num);
        attributes.addAttribute("skuId", skuId);
        return "redirect:http://cart.gulimall.com/addCartItemSuccess";
    }

    @RequestMapping("/addCartItemSuccess")
    public String addCartItemSuccess(@RequestParam("skuId") Long skuId,Model model) {
        CartItem CartItem = cartService.getCartItem(skuId);
        model.addAttribute("cartItem", CartItem);
        return "success";
    }


    @RequestMapping("/checkCart")
    public String checkCart(@RequestParam("isChecked") Integer isChecked,@RequestParam("skuId")Long skuId) {
        cartService.checkCart(skuId, isChecked);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @RequestMapping("/countItem")
    public String changeItemCount(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num) {
        cartService.changeItemCount(skuId, num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @RequestMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId) {
        cartService.deleteItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }


    @GetMapping("/currentUserCartItems")
    public List<CartItem> getcurrentUserCartItems() {
        return cartService.getUserCartItems();
    }
}
